package com.simple.api.base;

import com.simple.api.base.entity.ResponseModel;
import com.simple.api.base.enums.StateCode;
import com.simple.api.base.ex.EEException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

public class BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(BaseController.class);
    /**
     * 处理应用中所有的运行期异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionHandler(Exception ex) {
        LOG.error(String.format("发生异常错误, [%s]\n", ex));
        if (ex instanceof EEException) {
            return ((EEException) ex).getResponseModel();
        } else if (ex.getCause() != null && ex.getCause() instanceof EEException) {
            return ((EEException) ex.getCause()).getResponseModel();
        }else {
            StringBuilder sb = new StringBuilder();
            for (StackTraceElement set : ex.getStackTrace()) {
                sb.append(set + "\n");
            }
            LOG.error(String.format("详细信息, [%s]\n", sb.toString()));
            return new ResponseModel(StateCode.ERROR.code(), "服务器内部错误",null);
        }
    }


}
